/*
 * Created on Apr 19, 2005
 *
 */
package org.mushroomdb.jdbc;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.util.Properties;

import org.mushroomdb.exception.RDBMSRuntimeException;


/**
 * @author Matias
 *
 */
public class DriverImpl implements Driver {
	private static final int MAJOR = 0;
	private static final int MINOR = 1;
	private static final String URL_PREFIX = "jdbc:mushroomdb://"; //$NON-NLS-1$
	
	/**
	 * ClassLoad code
	 */
	static {
		Driver driver = new DriverImpl();
		try {
			DriverManager.registerDriver(driver);
		} catch (SQLException e) {
			throw new RDBMSRuntimeException(e);
		}
	}
	
	/**
	 * Default constructor
	 */
	public DriverImpl() {
	}

	/**
	 * @see java.sql.Driver#getMajorVersion()
	 */
	public int getMajorVersion() {
		return DriverImpl.MAJOR;
	}

	/**
	 * @see java.sql.Driver#getMinorVersion()
	 */
	public int getMinorVersion() {
		return DriverImpl.MINOR;
	}

	/**
	 * We just implement a little set of the standard. 
	 * @see java.sql.Driver#jdbcCompliant()
	 */
	public boolean jdbcCompliant() {
		return false;
	}

	/**
	 * URL Format:
	 * jdbc:mdlmdb://{server}:{port}/{database}
	 * @see java.sql.Driver#acceptsURL(java.lang.String)
	 */
	public boolean acceptsURL(String url) throws SQLException {
		boolean start = url.startsWith(URL_PREFIX);
		boolean length = url.substring(14).length() > 0;
		return start && length;
	}

	/**
	 * @see java.sql.Driver#connect(java.lang.String, java.util.Properties)
	 */
	public Connection connect(String url, Properties info) throws SQLException {
		if (this.acceptsURL(url)) {
			try {
				String shortUrl = url.substring(18);
				String serverName = shortUrl.substring(0,shortUrl.indexOf(':'));
				int port = Integer.parseInt(shortUrl.substring(shortUrl.indexOf(':') + 1,shortUrl.indexOf('/')));
				String databaseName = shortUrl.substring(shortUrl.indexOf('/') + 1);
				return new RDBMSConnectionDecorator(new ConnectionImpl(serverName, port, databaseName, info));
			} catch (Exception e) {
				throw new SQLException(e.getMessage());
			}
		} else {
			return null;
		}
	}

	/**
	 * @see java.sql.Driver#getPropertyInfo(java.lang.String, java.util.Properties)
	 */
	public DriverPropertyInfo[] getPropertyInfo(String arg0, Properties arg1) throws SQLException {
		return new DriverPropertyInfo[0];
	}

}
